const Role = require('../../../models/admin_role');
const Menu = require('../../../models/admin_menu');
const RoleOrMenu = require('../../../models/admin_menu_or_role');
const UserOrRole = require('../../../models/admin_user_or_role');

/**
 * 角色管理控制器
 */
const controllerRole = {
    /* 获取列表 */
    getList: async function (req, res, next) {
        try {
            let { per_page, page } = req.query;
            let pageSize = per_page ? per_page : 10;
            let params = {};
            let config = { pageSize, page }; //* 分页数据

            const roles = await Role.selectPaging(params, config);
            const dataList = await Role.all();
            let total = dataList.length;
            let number = Math.ceil(total / pageSize); //* 计算出总页数

            res.json({ code: 200, data: { list: roles, total, number } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 获取详情 */
    getById: async function (req, res, next) {
        try {
            let { id } = req.query;

            const roles = await Role.select({ id });

            res.json({ code: 200, data: roles[0] })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 新增 */
    Insert: async function (req, res, next) {
        try {
            let { name, status, remarks } = req.body;
            let params = { name, status, created_at: new Date().getTime() };

            const roleItem = await Role.select({ name });

            if (!name) return res.json({ code: 0, msg: '请输入角色名' });

            if (name.length <= 1 || name.length >= 16) return res.json({ code: 0, msg: '角色名长度2到16个字符' });

            if (roleItem.length > 0) return res.json({ code: 0, msg: '已创建该角色' })

            if (remarks) params.remarks = remarks;

            await Role.insert(params)

            res.json({ code: 200, msg: '新增成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 编辑 */
    update: async function (req, res, next) {
        try {
            let { id, name, status, remarks } = req.body;
            let params = { name, status, updated_at: new Date().getTime() };

            const roles = await Role.all();
            const roleItem = await Role.select({ id });
            const userItem = await UserOrRole.select({ role_id: id });

            roles.splice(roles.findIndex(e => e.id === id), 1); // 筛选除本id外的所有菜单列表
            let mime = roles.some(e => e.name === name); // 检索筛选的菜单列表中菜单名有没有相同

            if (status === 0) {
                if (userItem.length > 0) return res.json({ code: 0, msg: "有用户正在使用该角色,不能禁用" });
            }

            if (mime) return res.json({ code: 0, msg: "该角色名已存在" });

            if (name == roleItem[0].name && status == roleItem[0].status && remarks == roleItem[0].remarks) return res.json({ code: 0, msg: '未有任何修改' });

            if (remarks) params.remarks = remarks;

            await Role.update(id, params)

            res.json({ code: 200, msg: '编辑成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 删除 */
    del: async function (req, res, next) {
        try {
            let { id } = req.body;

            const role_or_menu = await RoleOrMenu.select({ role_id: id });
            const userItem = await UserOrRole.select({ role_id: id });

            if (id === 1) return res.json({ code: 0, msg: "该角色不能删除" });

            if (userItem.length > 0) return res.json({ code: 0, msg: "有用户正在使用该角色,不能删除" });

            if (role_or_menu.length > 0) await RoleOrMenu.delete(role_or_menu[0].id);

            await Role.delete(id)

            res.json({ code: 200, msg: '删除成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 获取菜单列表 */
    getMenuList: async function (req, res, next) {
        try {
            const menuList = await Menu.all();
            res.json({ code: 200, data: menuList })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 获取授权列表 */
    getAuthList: async function (req, res, next) {
        try {
            let { role_id } = req.query;

            const role_or_menu = await RoleOrMenu.select({ role_id });

            res.json({ code: 200, msg: '获取角色权限ID成功', data: role_or_menu[0].menu_ids })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 角色授权 */
    updateAuth: async function (req, res, next) {
        try {
            let { role_id, menu_id } = req.body;

            let menu_ids = menu_id.toString();

            const role_or_menu = await RoleOrMenu.select({ role_id });

            if (role_or_menu.length > 0) {

                let id = role_or_menu[0].id;

                await RoleOrMenu.update(id, { menu_ids })

                return res.json({ code: 200, msg: '已成功修改角色权限' })
            } else {

                await RoleOrMenu.insert({ role_id, menu_ids })

                res.json({ code: 200, msg: '授权成功' })
            }

        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
}

module.exports = controllerRole;